package cn.fl.riskctrl.corp.service.impl;

import java.util.*;

import cmm.comm.facade.framework.api.ISysDictionaryApiService;
import cmm.mid.core.framework.dto.DataResultDTO;
import cn.cmm.base.framework.constant.BaseConstant;
import cn.cmm.cache.framework.utils.PropertiesCacheUtils;
import cn.fl.commons.result.ResponseData;
import cn.fl.framework.base.context.CurrentThreadContext;
import cn.fl.riskctrl.corp.vo.RcWlTpMgtVO;
import fl.constant.facade.framework.constant.DictionaryConstant;
import fl.constant.facade.framework.constant.FlowConstant;
import fl.constant.facade.framework.constant.SystemConstant;
import fl.riskctrl.facade.xjkj.condition.XJKJCreditRecordResultQC;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import cn.fl.riskctrl.corp.service.IRcCstCorpBscInfoService;
import cn.fl.riskctrl.corp.vo.RcCstCorpBscInfoVO;
import cn.cmm.base.framework.constant.BaseExceptionConstant;
import cn.cmm.base.framework.exception.BaseException;
import cn.cmm.base.framework.utils.BaseLogUtils;
import cn.cmm.base.framework.utils.CollectionUtils;
import cn.cmm.base.framework.utils.StringUtils;
import cmm.mid.core.framework.page.Pager;
import rc.corpbaseinfo.base.dto.PageResponseDTO;
import rc.corpbaseinfo.facade.corpbaseinfo.api.IRcCorpModifyApiService;
import rc.corpbaseinfo.facade.corpbaseinfo.api.IRcCorpQueryApiService;
import rc.corpbaseinfo.facade.corpbaseinfo.condition.RcCstCorpBscInfoQC;
import rc.corpbaseinfo.facade.corpbaseinfo.dto.RcCstCorpBscInfoDTO;
import rc.corpbaseinfo.facade.corpbaseinfo.dto.RcWlTpMgtDTO;
import rctc.rmyhcorp.facade.external.api.IRcXjcorpApplySearchApiService;
import rctc.rmyhcorp.facade.external.condition.RcXjcorpSearchQC;


/**
 * @Description: RC_CST_CORP_BSC_INFO（前置征信企业客户基础信息） 客户端服务层接口实现
 * @Description: 业务层方法名称前缀：新增：add* 删除：remove* 修改：modify* 查询对象：select* get* 批量：batch* 查询集合：search*
 */
@Service
public class RcCstCorpBscInfoServiceImpl implements IRcCstCorpBscInfoService {

	/**
	 * 自定义 API 自行注入需要的API服务
	 */
	@Autowired
	private IRcCorpQueryApiService rcCorpQueryApiService;
    @Autowired
    private ISysDictionaryApiService sysDictionaryApiService;
    @Autowired
    private IRcCorpModifyApiService rcCorpModifyApiService;
    @Autowired
    private IRcXjcorpApplySearchApiService rcXjcorpApplySearchApiService;

	@Override
	public RcCstCorpBscInfoVO selectById(Long id) throws BaseException{
		if(StringUtils.isEmpty(id)){
            BaseLogUtils.newLogger( "主键参数不能为空!", CurrentThreadContext.getCurrentUserName()).info();
			throw new BaseException(BaseExceptionConstant.BASE_EXCEPTION_CODE_600, "获取对象主键不能为空!");
		}
		ResponseData<RcCstCorpBscInfoDTO> responseData = rcCorpQueryApiService.selectRcCstCorpBscInfoDTOById(id);
        if(Objects.equals(responseData.getCode(),ResponseData.SUCCESS_CODE)){
            RcCstCorpBscInfoDTO dto = responseData.getData();
            RcCstCorpBscInfoVO vo = new RcCstCorpBscInfoVO();
            BeanUtils.copyProperties(dto,vo);
            return vo;
        }
		return null;
	}

	@Override
	public Long add(RcCstCorpBscInfoVO entity) throws BaseException{
		if(null == entity){
			throw new BaseException(BaseExceptionConstant.BASE_EXCEPTION_CODE_600,"新增对象不存在!");
		}
		//return this.rcCstCorpBscInfoApiService.add(RcCstCorpBscInfoVOTransform.toDTO(entity));
		return null;
	}

	@Override
	public boolean modify(RcCstCorpBscInfoVO entity) throws BaseException{
		if(null == entity){
			throw new BaseException(BaseExceptionConstant.BASE_EXCEPTION_CODE_600,"修改对象不能为空!");
		}
        RcCstCorpBscInfoDTO dto = new RcCstCorpBscInfoDTO();
        BeanUtils.copyProperties(entity, dto);
        Date date = new Date();
        dto.setMdfUsrId(CurrentThreadContext.getCurrentUserId());
        dto.setMdfTm(date);
        ResponseData responseData = rcCorpModifyApiService.modifyRcCstCorpBscInfo(dto);
        if(Objects.equals(responseData.getCode(),ResponseData.SUCCESS_CODE)){
            return true;
        }else{
            throw new BaseException(responseData.getMessage());
        }
	}

	@Override
	public Pager searchListPage(int pageSize, int pageNum, RcCstCorpBscInfoQC qc) throws BaseException{
		ResponseData<PageResponseDTO<RcCstCorpBscInfoDTO>> responseData = this.rcCorpQueryApiService.searchRcCstCorpBscInfoListPage(pageSize, pageNum, qc);

		List<String> codeGrpCdList = new ArrayList<>();
        // 征信级别
//        String rskLvlCdDic = PropertiesCacheUtils.getProperty(DictionaryConstant.CODE_RCT_LVL_CD);
        // 审核状态
        String audStsCdDic = "RCT0046";
        String corpCertTypCdDic = "RCT0044";
		codeGrpCdList.add(corpCertTypCdDic);
//		codeGrpCdList.add(rskLvlCdDic);
		codeGrpCdList.add(audStsCdDic);
		Map<String, String> corpCertTypCdMap = new HashMap<>();
        Map<String, String> audStsCdMap = new HashMap<>();
//        Map<String, String> rskLvlCdMap = new HashMap<>();
		Map<String, Map<String, String>> dicMap = null;
		String sysCd = PropertiesCacheUtils.getProperty(SystemConstant.FL_SERVICE_CD);
		String orgCd = PropertiesCacheUtils.getProperty(SystemConstant.FL_ORG_CD);
		dicMap = this.sysDictionaryApiService.searchMultiGroupToMap(sysCd, orgCd, codeGrpCdList);
		if(dicMap.containsKey(corpCertTypCdDic)){
			corpCertTypCdMap = dicMap.get(corpCertTypCdDic);
			if(CollectionUtils.isMapEmpty(corpCertTypCdMap)){
				corpCertTypCdMap = new HashMap<>();
			}
		}
//        if (dicMap.containsKey(rskLvlCdDic)) {
//            rskLvlCdMap = dicMap.get(rskLvlCdDic);
//            if (CollectionUtils.isMapEmpty(rskLvlCdMap)) {
//                rskLvlCdMap = new HashMap<>();
//            }
//        }
        if (dicMap.containsKey(audStsCdDic)) {
            audStsCdMap = dicMap.get(audStsCdDic);
            if (CollectionUtils.isMapEmpty(audStsCdMap)) {
                audStsCdMap = new HashMap<>();
            }
        }
		Pager pager = new Pager();
		if (Objects.equals(responseData.getCode(),ResponseData.SUCCESS_CODE)) {
			PageResponseDTO pageDto = responseData.getData();
			if (null != pageDto) {
				List<RcCstCorpBscInfoVO> list = new ArrayList<>();
                Map<Integer, String> yesNoMap = BaseConstant.getYesNoMap;
				for(Object dto : pageDto.getList()){
					RcCstCorpBscInfoVO vo = new RcCstCorpBscInfoVO();
					BeanUtils.copyProperties(dto,vo);
                    if (StringUtils.isNotEmpty(vo.getCertTypCd())) {
                        vo.setCertTypCdNm(corpCertTypCdMap.get(vo.getCertTypCd()));
                    }
                    if (StringUtils.isNotEmpty(vo.getIsValid())) {
                        vo.setIsValidNm(yesNoMap.get(vo.getIsValid()));
                    }
                    if (StringUtils.isNotEmpty(vo.getIsReaud())) {
                        vo.setIsReaudNm(yesNoMap.get(vo.getIsReaud()));
                    }
//                    if (StringUtils.isNotEmpty(vo.getRskLeveCd())) {
//                        vo.setRskLeveCdNm(rskLvlCdMap.get(vo.getRskLeveCd()));
//                    }
                    if (StringUtils.isNotEmpty(vo.getAudStsCd())) {
                        vo.setAudStsCdNm(audStsCdMap.get(vo.getAudStsCd()));
                    }
					list.add(vo);
				}
				pager.setTotalCount(pageDto.getTotalCount());
				pager.setResultList(list);
			}
		}
		return pager;
	}

    @Override
    public DataResultDTO getRiskCtrlData(Long cstId) {
        DataResultDTO result = new DataResultDTO(BaseConstant.IS_YESNO_YES);
        ResponseData<RcCstCorpBscInfoDTO> responseData = rcCorpQueryApiService.selectRcCstCorpBscInfoDTOById(cstId);
        if(Objects.equals(responseData.getCode(),ResponseData.SUCCESS_CODE)){
            Map<String, String> map = new HashMap<>();
            RcCstCorpBscInfoDTO dto = responseData.getData();
            String audStsCd = dto.getAudStsCd();
            if (StringUtils.isNotEmpty(audStsCd) && PropertiesCacheUtils.getProperty(FlowConstant.FLOW_CHECK_STATE_NO_PASS).equals(audStsCd)) {
                map.put("refuse-pass", "false");
            } else if (StringUtils.isNotEmpty(audStsCd) && PropertiesCacheUtils.getProperty(FlowConstant.FLOW_CHECK_STATE_PASS).equals(audStsCd)) {
                map.put("refuse-pass", "true");
            } else if (StringUtils.isNotEmpty(audStsCd) && PropertiesCacheUtils.getProperty(FlowConstant.FLOW_CHECK_STATE_IN).equals(audStsCd)) {
                map.put("refuse-pass", "audit");
            } else if (StringUtils.isNotEmpty(audStsCd) && PropertiesCacheUtils.getProperty(FlowConstant.FLOW_CHECK_STATE_NON).equals(audStsCd)) {
                map.put("refuse-pass", "commit");
            } else if (StringUtils.isNotEmpty(audStsCd) && "4".equals(audStsCd)) {
                map.put("refuse-pass", "audit1");
            } else if (StringUtils.isNotEmpty(audStsCd) && "5".equals(audStsCd)) {
                map.put("refuse-pass", "audit2");
            } else {
                map.put("refuse-pass", "error");
            }

            String hitRule = dto.getHitRule();
            map.put("refuse", hitRule);  // 匹配结果
            result.setData(map);
        } else {
            throw new BaseException(BaseExceptionConstant.BASE_EXCEPTION_CODE_600,"获取拒单规则信息异常!");
        }
        return result;
    }

    @Override
    public DataResultDTO getXjCorpLocalData(Long cstId) {
        DataResultDTO result = new DataResultDTO(BaseConstant.IS_YESNO_YES);
        Map<String, String> map = new HashMap<>();
        RcXjcorpSearchQC qc = new RcXjcorpSearchQC();
        ResponseData<RcCstCorpBscInfoDTO> responseData = rcCorpQueryApiService.selectRcCstCorpBscInfoDTOById(cstId);
        if(Objects.equals(responseData.getCode(),ResponseData.SUCCESS_CODE)){
            RcCstCorpBscInfoDTO data = responseData.getData();
            qc.setpId(data.getPid());
            qc.setbId(data.getBid());
        }
        qc.setDataId(cstId);
        DataResultDTO data = rcXjcorpApplySearchApiService.getRcXjcorpApplyByDataId(qc);
        String localHTMLPathInfo = (String) data.getData();
//        String localHTMLPathInfo = "attachments/11000/riskctrl/xjnp2/html/20201020/bb84ed9e-6300-4f56-9159-82e163628616.html";
        String xjHtmlPath = "";
        if(StringUtils.isEmpty(localHTMLPathInfo)){
            map.put("xj-pass", "false");
            map.put("xj", "");
        }else{
            map.put("xj-pass", "true");
            map.put("xj", "升级中...");
            xjHtmlPath=localHTMLPathInfo;

        }
        map.put("xj-path", xjHtmlPath);

        result.setData(map);
        return result;
    }
}
